from PyQt4 import QtGui,QtCore
from ftllibs.FTL import MasteriesDS
from ftllibs.FTL import MASTERIES


class MasteriesTab(QtGui.QWidget):
    def __init__(self,parent = None):
        super(MasteriesTab,self).__init__()
        self.MasterLayout = QtGui.QGridLayout()
        self.setLayout(self.MasterLayout)
        self.view = QtGui.QListView()
        self.model=MasteriesDS.GetMasteriesDataModel()
        self.view.setModel(self.model)
        self.MasteriesDisplay=MasteriesDisplay(self)
        self.AddButton = QtGui.QPushButton('Add')
        self.SaveButton = QtGui.QPushButton('Save')
        self.MasterLayout.addWidget(self.AddButton,0,0,1,1)
        self.MasterLayout.addWidget(self.SaveButton,1,0,1,1)
        self.MasterLayout.addWidget(self.view,2,0,1,1)
        self.DisplayGrid=QtGui.QGridLayout()
        self.PointsAvailableLabel = QtGui.QLabel("<h1>Points Available: %s</h1>" % (30))
        self.MasteriesNameLabel=QtGui.QLabel("<h1>Unnamed Masteries</h1>")
        self.DisplayGrid.addWidget(self.MasteriesNameLabel,0,0,1,1)
        self.DisplayGrid.addWidget(self.MasteriesDisplay,1,0,1,1)
        self.DisplayGrid.addWidget(self.PointsAvailableLabel,2,0,1,1,QtCore.Qt.AlignRight)
        self.DisplayGrid.setRowStretch(3,1)
        self.MasterLayout.addLayout(self.DisplayGrid,0,1,3,1)
        self.unsaved=False
        self.NewMasteries=True
        self.AddButton.clicked.connect(self.AddMastery)
        self.SaveButton.clicked.connect(self.SaveMastery)
        self.view.clicked.connect(self.LoadMasteries)


    def AddMastery(self):
        text,ok = QtGui.QInputDialog.getText(self,'Add New Masteries','Name your Masteries setup:',text='Unsaved Masteries')
        if ok:
            lastrow=self.model.rowCount()
            print "AddMastery: lastrow: ", lastrow
            self.model.insertRows(lastrow,1,text)
            index = self.model.createIndex(lastrow,0)
            self.view.setCurrentIndex(index)
            if self.NewMasteries:
                self.NewMasteries=False
                self.SaveMastery()
                self.LoadMasteries()
            else:
                self.LoadMasteries()

    def DeleteMastery(self):
        ok = QtGui.QMessageBox.question(self,'Delete Mastery',"Do you realy want to delete: %s" % (self.MasteriesDisplay.name),"Yes","No")
        if ok == 0:
            index = self.view.currentIndex()
            self.model.removeRows(index.row(),1)

    def SaveMastery(self):
        if self.NewMasteries:
            self.AddMastery()
        else:
            masteries = self.MasteriesDisplay.GetMasteries()
            self.model.saveMasteries(masteries)
            self.unsaved=False

    def LoadMasteries(self):
        print "Load Masteries Called"
        self.CheckSave()
#        self.MasteriesDisplay.ResetMasteries()
        index=self.view.currentIndex()
        MID=self.model.getMID(index.row())
        masteries=self.model.loadMasteries(MID)
        self.MasteriesDisplay.SetMasteries(masteries)
        self.MasteriesNameLabel.setText("<h1>%s</h1>" % (masteries['name']))
        self.NewMasteries=False
        self.unsaved=False

#    def RequestClose(self):
#        print "BuildTab -> RequestClose called"
#        self.close()

    def CheckSave(self):
        if self.unsaved:
            ok = QtGui.QMessageBox.question(self,'Save Changes ?',"Do you want to save your changes ?","Yes","No")
            if ok == 0:
                self.SaveMastery()


class MasteriesDisplay(QtGui.QWidget):
    def __init__(self,parent = None):
        super(MasteriesDisplay,self).__init__()
        self.parent=parent
        self.setFixedSize(828,479)
        self.MasteriesBG = QtGui.QPixmap('images/ui/MasteriesBG.png')
        self.InitClickRecs()
        self.InitIcons()
        self.TotalPoints=0
        self.MaxPoints=30
        self.OffensivePoints=0
        self.DefensivePoints=0
        self.UtilityPoints=0
        self.OffensivePointsRect=QtCore.QRectF(23,444,236,26)
        self.DefensivePointsRect=QtCore.QRectF(297,444,236,26)
        self.UtilityPointsRect=QtCore.QRectF(570,444,236,26)
        self.pen = QtGui.QPen()
        self.pen.setColor(QtGui.QColor(0,240,0))
        self.pen.setWidth(2)
        self.whitepen = QtGui.QPen()
        self.whitepen.setColor(QtGui.QColor(255,255,255))
        self.whitepen.setWidth(2)
        self.redpen = QtGui.QPen()
        self.redpen.setColor(QtGui.QColor(240,0,0))
        self.redpen.setWidth(2)
        self.bluepen = QtGui.QPen()
        self.bluepen.setColor(QtGui.QColor(0,0,240))
        self.bluepen.setWidth(2)
        self.brush = QtGui.QBrush()
        self.brush.setColor(QtGui.QColor(0,0,0))
        self.brush.setStyle(1)
  
    def InitIcons(self):
        self.IconList={}
        for i in self.ClickRects.keys():
            self.IconList[i]=MasteriesIcon(i,MASTERIES.MasteriesLimitList[i],parent=self)
            self.IconList[i].move(self.ClickRects[i].x(),self.ClickRects[i].y())
            self.IconList[i].LeftClicked.connect(self.addMasteryPoint)
            self.IconList[i].RightClicked.connect(self.removeMasteryPoint)
        # enable first set of icons
        #attack
        self.IconList['SummonersWrath'].SetEnable()
        self.IconList['BruteForce'].SetEnable()
        self.IconList['MentalForce'].SetEnable()
        self.IconList['Butcher'].SetEnable()
        # defense
        self.IconList['SummonersResolve'].SetEnable()
        self.IconList['Resistance'].SetEnable()
        self.IconList['Hardiness'].SetEnable()
        self.IconList['ToughSkin'].SetEnable()
        # utility
        self.IconList['SummonersInsight'].SetEnable()
        self.IconList['GoodHands'].SetEnable()
        self.IconList['ExpandedMind'].SetEnable()
        self.IconList['ImprovedRecall'].SetEnable()

    def SetMasteries(self,masteries):
        self.ResetMasteries()
        for key,value in masteries.iteritems():
            print key,value
            if key == "MID" or key == "name" or key == "position":
                continue
            if int(value) != 0:
                self.IconList[key].SetEnable()
                for i in range(int(value)):
                    self.addMasteryPoint(key)
#                self.IconList[key].currentvalue=int(value)
        self.update()
        
    def ResetMasteries(self):
        for i in self.IconList:
            self.IconList[i].SetDisable()
            self.IconList[i].currentvalue=0
        self.TotalPoints=0
        self.OffensivePoints=0
        self.DefensivePoints=0
        self.UtilityPoints=0
        self.IconList['SummonersWrath'].SetEnable()
        self.IconList['BruteForce'].SetEnable()
        self.IconList['MentalForce'].SetEnable()
        self.IconList['Butcher'].SetEnable()
        # defense
        self.IconList['SummonersResolve'].SetEnable()
        self.IconList['Resistance'].SetEnable()
        self.IconList['Hardiness'].SetEnable()
        self.IconList['ToughSkin'].SetEnable()
        # utility
        self.IconList['SummonersInsight'].SetEnable()
        self.IconList['GoodHands'].SetEnable()
        self.IconList['ExpandedMind'].SetEnable()
        self.IconList['ImprovedRecall'].SetEnable()
        self.parent.PointsAvailableLabel.setText("<h1>Points Available: %s</h1>" % (30))
    
    def addMasteryPoint(self,mastery):
        if self.TotalPoints < self.MaxPoints:
            if self.IconList[str(mastery)].addPoint():
                self.TotalPoints += 1
                if mastery in MASTERIES.OffensiveMasteriesList:
                    self.OffensivePoints +=1
                if mastery in MASTERIES.DefensiveMasteriesList:
                    self.DefensivePoints +=1
                if mastery in MASTERIES.UtilityMasteriesList:
                    self.UtilityPoints += 1
            self.CheckEnableStatus()
        self.parent.PointsAvailableLabel.setText("<h1>Points Available: %s</h1>" % (int(self.MaxPoints) - int(self.TotalPoints)))

    def removeMasteryPoint(self,mastery):
        if self.TotalPoints > 0:
            if self.IconList[str(mastery)].removePoint():
                self.TotalPoints -= 1
                if mastery in MASTERIES.OffensiveMasteriesList:
                    self.OffensivePoints -=1
                if mastery in MASTERIES.DefensiveMasteriesList:
                    self.DefensivePoints -=1
                if mastery in MASTERIES.UtilityMasteriesList:
                    self.UtilityPoints -= 1
            self.CheckEnableStatus()

    def GetMasteries(self):
        masteries = {}
        for i in self.IconList:
            masteries[i]=self.IconList[i].currentvalue
        return masteries

    def CheckEnableStatus(self):
        print self.OffensivePoints
        print self.DefensivePoints
        print self.UtilityPoints
        print self.TotalPoints
        if self.OffensivePoints >= 4:
            self.IconList['Alacrity'].SetEnable()
            self.IconList['Sorcery'].SetEnable()
            self.IconList['Demolitionist'].SetEnable()
        else:
            self.IconList['Alacrity'].SetDisable()
            self.IconList['Sorcery'].SetDisable()
            self.IconList['Demolitionist'].SetDisable()

        if self.OffensivePoints >= 8:
            self.IconList['Deadliness'].SetEnable()
            if self.IconList['Alacrity'].isMaxed():
                self.IconList['WeaponsExpertise'].SetEnable()
            else:
                self.IconList['WeaponsExpertise'].SetDisable()
            if self.IconList['Sorcery'].isMaxed():
                self.IconList['ArcaneKnowledge'].SetEnable()
            else:
                self.IconList['ArcaneKnowledge'].SetDisable()
            self.IconList['Havoc'].SetEnable()
        else:
            self.IconList['Deadliness'].SetDisable()
            self.IconList['WeaponsExpertise'].SetDisable()
            self.IconList['ArcaneKnowledge'].SetDisable()
            self.IconList['Havoc'].SetDisable()

        if self.OffensivePoints >= 12:
            if self.IconList['Deadliness'].isMaxed():
                self.IconList['Lethality'].SetEnable()
            else:
                self.IconList['Lethality'].SetDisable()
            self.IconList['Vampirism'].SetEnable()
            self.IconList['Blast'].SetEnable()
        else:
            self.IconList['Lethality'].SetDisable()
            self.IconList['Vampirism'].SetDisable()
            self.IconList['Blast'].SetDisable()

        if self.OffensivePoints >= 16:
            self.IconList['Sunder'].SetEnable()
            self.IconList['Archmage'].SetEnable()
        else:
            self.IconList['Sunder'].SetDisable()
            self.IconList['Archmage'].SetDisable()

        if self.OffensivePoints >= 20:
            self.IconList['Executioner'].SetEnable()

        if self.DefensivePoints >= 4:
            self.IconList['Durability'].SetEnable()
            self.IconList['Vigor'].SetEnable()
        else:
            self.IconList['Durability'].SetDisable()
            self.IconList['Vigor'].SetDisable()

        if self.DefensivePoints >= 8:
            self.IconList['Indomitable'].SetEnable()
            self.IconList['Evasion'].SetEnable()
            if self.IconList['ToughSkin'].isMaxed():
                self.IconList['BladedArmor'].SetEnable()
            else:
                self.IconList['BladedArmor'].SetDisable()
            if self.IconList['Durability'].isMaxed():
                self.IconList['VeteransScars'].SetEnable()
            else:
                self.IconList['VeteransScars'].SetDisable()
        else:
            self.IconList['Indomitable'].SetDisable()
            self.IconList['Evasion'].SetDisable()
            self.IconList['BladedArmor'].SetDisable()
            self.IconList['VeteransScars'].SetDisable()

        if self.DefensivePoints >= 12:
            self.IconList['SiegeCommander'].SetEnable()
            self.IconList['Initiator'].SetEnable()
            self.IconList['Enlightenment'].SetEnable()

        else:
            self.IconList['SiegeCommander'].SetDisable()
            self.IconList['Initiator'].SetDisable()
            self.IconList['Enlightenment'].SetDisable()

        if self.DefensivePoints >= 16:
            self.IconList['Mercenary'].SetEnable()
            self.IconList['HonorGuard'].SetEnable()
        else:
            self.IconList['Mercenary'].SetDisable()
            self.IconList['HonorGuard'].SetDisable()
            
        if self.DefensivePoints >= 20:
            self.IconList['Juggernaut'].SetEnable()
        else:
            self.IconList['Juggernaut'].SetDisable()



        if self.UtilityPoints >= 4:
            self.IconList['Swiftness'].SetEnable()
            self.IconList['Meditation'].SetEnable()
            self.IconList['Scout'].SetEnable()
        else:
            self.IconList['Swiftness'].SetDisable()
            self.IconList['Meditation'].SetDisable()
            self.IconList['Scout'].SetDisable()
            
        if self.UtilityPoints >= 8:
            self.IconList['Greed'].SetEnable()
            self.IconList['Transmutation'].SetEnable()
            self.IconList['RunicAffinity'].SetEnable()
        else:
            self.IconList['Greed'].SetDisable()
            self.IconList['Transmutation'].SetDisable()
            self.IconList['RunicAffinity'].SetDisable()

        if self.UtilityPoints >= 12:
            if self.IconList['Greed'].isMaxed():
                self.IconList['Wealth'].SetEnable()
            else:
                self.IconList['Wealth'].SetDisable()
            self.IconList['Awareness'].SetEnable()
            self.IconList['Sage'].SetEnable()
        else:
            self.IconList['Wealth'].SetDisable()
            self.IconList['Awareness'].SetDisable()
            self.IconList['Sage'].SetDisable()
            
        if self.UtilityPoints >= 16:
            self.IconList['StrengthOfSpirit'].SetEnable()
            self.IconList['Intelligence'].SetEnable()
        else:
            self.IconList['StrengthOfSpirit'].SetDisable()
            self.IconList['Intelligence'].SetDisable()

        if self.UtilityPoints >= 20:
            self.IconList['Mastermind'].SetEnable()
        else:
            self.IconList['Mastermind'].SetDisable()
        self.update()

    def InitClickRecs(self):
        self.ClickRects={}
        self.ClickRects['SummonersWrath']=QtCore.QRect(20,12,58,58)
        self.ClickRects['BruteForce']=QtCore.QRect(82,12,58,58)
        self.ClickRects['MentalForce']=QtCore.QRect(144,12,58,58)
        self.ClickRects['Butcher']=QtCore.QRect(206,12,58,58)
        self.ClickRects['Alacrity']=QtCore.QRect(82,82,58,58)
        self.ClickRects['Sorcery']=QtCore.QRect(144,82,58,58)
        self.ClickRects['Demolitionist']=QtCore.QRect(206,82,58,58)
        self.ClickRects['Deadliness']=QtCore.QRect(20,154,58,58)
        self.ClickRects['WeaponsExpertise']=QtCore.QRect(82,154,58,58)
        self.ClickRects['ArcaneKnowledge']=QtCore.QRect(144,154,58,58)
        self.ClickRects['Havoc']=QtCore.QRect(206,154,58,58)
        self.ClickRects['Lethality']=QtCore.QRect(20,226,58,58)
        self.ClickRects['Vampirism']=QtCore.QRect(82,226,58,58)
        self.ClickRects['Blast']=QtCore.QRect(144,226,58,58)
        self.ClickRects['Sunder']=QtCore.QRect(82,298,58,58)
        self.ClickRects['Archmage']=QtCore.QRect(144,298,58,58)
        self.ClickRects['Executioner']=QtCore.QRect(82,368,58,58)
        #defensive
        self.ClickRects['SummonersResolve']=QtCore.QRect(294,12,58,58)
        self.ClickRects['Resistance']=QtCore.QRect(356,12,58,58)
        self.ClickRects['Hardiness']=QtCore.QRect(418,12,58,58)
        self.ClickRects['ToughSkin']=QtCore.QRect(480,12,58,58)
        self.ClickRects['Durability']=QtCore.QRect(356,82,58,58)
        self.ClickRects['Vigor']=QtCore.QRect(418,82,58,58)
        self.ClickRects['Indomitable']=QtCore.QRect(294,154,58,58)
        self.ClickRects['VeteransScars']=QtCore.QRect(356,154,58,58)
        self.ClickRects['Evasion']=QtCore.QRect(418,154,58,58)
        self.ClickRects['BladedArmor']=QtCore.QRect(480,154,58,58)
        self.ClickRects['SiegeCommander']=QtCore.QRect(294,226,58,58)
        self.ClickRects['Initiator']=QtCore.QRect(356,226,58,58)
        self.ClickRects['Enlightenment']=QtCore.QRect(418,226,58,58)
        self.ClickRects['HonorGuard']=QtCore.QRect(356,298,58,58)
        self.ClickRects['Mercenary']=QtCore.QRect(418,298,58,58)
        self.ClickRects['Juggernaut']=QtCore.QRect(356,368,58,58)
        # util
        self.ClickRects['SummonersInsight']=QtCore.QRect(568,12,58,58)
        self.ClickRects['GoodHands']=QtCore.QRect(630,12,58,58)
        self.ClickRects['ExpandedMind']=QtCore.QRect(692,12,58,58)
        self.ClickRects['ImprovedRecall']=QtCore.QRect(754,12,58,58)
        self.ClickRects['Swiftness']=QtCore.QRect(630,82,58,58)
        self.ClickRects['Meditation']=QtCore.QRect(692,82,58,58)
        self.ClickRects['Scout']=QtCore.QRect(754,82,58,58)
        self.ClickRects['Greed']=QtCore.QRect(630,154,58,58)
        self.ClickRects['Transmutation']=QtCore.QRect(692,154,58,58)
        self.ClickRects['RunicAffinity']=QtCore.QRect(754,154,58,58)
        self.ClickRects['Wealth']=QtCore.QRect(630,226,58,58)
        self.ClickRects['Awareness']=QtCore.QRect(692,226,58,58)
        self.ClickRects['Sage']=QtCore.QRect(754,226,58,58)
        self.ClickRects['StrengthOfSpirit']=QtCore.QRect(630,298,58,58)
        self.ClickRects['Intelligence']=QtCore.QRect(692,298,58,58)
        self.ClickRects['Mastermind']=QtCore.QRect(692,368,58,58)
        
    def paintEvent(self,e):
        painter = QtGui.QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        painter.drawPixmap(0,0,self.MasteriesBG)
        painter.fillRect(self.OffensivePointsRect,self.brush)
        painter.fillRect(self.DefensivePointsRect,self.brush)
        painter.fillRect(self.UtilityPointsRect,self.brush)
        painter.drawRect(self.OffensivePointsRect)
        painter.drawRect(self.DefensivePointsRect)
        painter.drawRect(self.UtilityPointsRect)
        painter.setPen(self.whitepen)
        painter.drawText(self.OffensivePointsRect,"Offense: %s" % (self.OffensivePoints),QtGui.QTextOption(QtCore.Qt.AlignCenter))
        painter.drawText(self.DefensivePointsRect,"Defense: %s" % (self.DefensivePoints),QtGui.QTextOption(QtCore.Qt.AlignCenter))
        painter.drawText(self.UtilityPointsRect,"Utility: %s" % (self.UtilityPoints),QtGui.QTextOption(QtCore.Qt.AlignCenter))

class MasteriesIcon(QtGui.QWidget):
    LeftClicked = QtCore.pyqtSignal([str])
    RightClicked = QtCore.pyqtSignal([str])
    def __init__(self,name,maxvalue,parent = None):
        super(MasteriesIcon,self).__init__(parent)
        self.parent=parent
        self.setFixedSize(58,58)
        self.name = name
        self.Pixmap=QtGui.QPixmap('images/masteries/%s.png' % (self.name))
        self.im = self.Pixmap.toImage()
        for i in range(self.im.width()):
            for j in range(self.im.height()):
                col = self.im.pixel(i,j)
                gray = QtGui.qGray(col)
                self.im.setPixel(i,j,QtGui.qRgb(gray,gray,gray))
        self.maxvalue = maxvalue
        self.currentvalue = 0
        self.enabled = False
        self.PointsRect=QtCore.QRectF(30,42,27,15)
        self.pen = QtGui.QPen()
        self.pen.setColor(QtGui.QColor(0,240,0))
        self.pen.setWidth(2)
        self.GrayPen = QtGui.QPen()
        self.GrayPen.setColor(QtGui.QColor(128,128,128))
        self.GrayPen.setWidth(2)
        self.brush = QtGui.QBrush()
        self.brush.setColor(QtGui.QColor(0,0,0))
        self.brush.setStyle(1)

    def enterEvent(self,e):
        print "entered: ",self.name

    def mouseReleaseEvent(self,e):
        if self.enabled:
            if e.button() == QtCore.Qt.LeftButton:
                self.LeftClicked.emit(self.name)
            if e.button() == QtCore.Qt.RightButton:
                self.RightClicked.emit(self.name)

    def isMaxed(self):
        if self.currentvalue == self.maxvalue:
            return True
        else:
            return False

    def addPoint(self):
        if self.currentvalue == self.maxvalue:
            return False
        else:
            self.currentvalue += 1
            self.update()
            return True
            
    def removePoint(self):
        if self.currentvalue == 0:
            return False
        else:
            
            self.currentvalue -= 1
#            print self.currentvalue 
            self.update()
            return True
        
    def paintEvent(self,e):
        painter = QtGui.QPainter(self)
        painter.setPen(self.pen)
        if self.enabled:
            painter.drawPixmap(0,0,self.Pixmap)
        else:
            painter.setPen(self.GrayPen)
            painter.drawImage(0,0,self.im)
        painter.fillRect(self.PointsRect,self.brush)
        painter.drawRect(self.PointsRect)
        painter.drawText(self.PointsRect,"%s/%s" % (self.currentvalue,self.maxvalue),QtGui.QTextOption(QtCore.Qt.AlignCenter))

    def SetEnable(self):
        self.enabled = True

    def SetDisable(self):
        self.enabled = False